Grokking Google Coding Interview
Rate this course
Ask Author
Contribute
Back to course home

0% completed

Vote For New Content
Introduction
Who Should Take This Course?
Google Easy
Add Binary (easy)
Solution: Add Binary
Valid Mountain Array (easy)
Solution: Valid Mountain Array
Set Mismatch (easy)
Solution: Set Mismatch
Is Subsequence (easy)
Solution: Is Subsequence
Length of Last Word (easy)
Solution: Length of Last Word
Search Insert Position (easy)
Solution: Search Insert Position
Repeated Substring Pattern (easy)
Solution: Repeated Substring Pattern
Monotonic Array (easy)
Solution: Monotonic Array
Count Nodes Equal to Average of Subtree (easy)
Solution: Count Nodes Equal to Average of Subtree
Find the Difference (easy)
Solution: Find the Difference
How Many Numbers Are Smaller Than the Current Number (easy)
Solution: How Many Numbers Are Smaller Than the Current Number
Binary Tree Paths (easy)
Solution: Binary Tree Paths
Find the Difference of Two Arrays (easy)
Solution: Find the Difference of Two Arrays
Merge Strings Alternately (easy)
Solution: Merge Strings Alternately
Reverse a LinkedList (easy)
Solution: Reverse a LinkedList
Gray Code (medium)
Solution: Gray Code
2 Keys Keyboard (medium)
Solution: 2 Keys Keyboard
Arithmetic Slices (medium)
Solution: Arithmetic Slices
Unique Length-3 Palindromic Subsequences (medium)
Solution: Unique Length-3 Palindromic Subsequences
Minimum Difference Between Largest and Smallest Value in Three Moves (medium)
Solution: Minimum Difference Between Largest and Smallest Value in Three Moves
Letter Combinations of a Phone Number (medium)
Solution: Letter Combinations of a Phone Number
01 Matrix (medium)
Solution: 01 Matrix
Maximum Points You Can Obtain from Cards (medium)
Solution: Maximum Points You Can Obtain from Cards
Strobogrammatic Number II (medium)
Solution: Strobogrammatic Number II
Maximum Length of Semi-Decreasing Subarrays (medium)
Solution: Maximum Length of Semi-Decreasing Subarrays
Minimum Area Rectangle (medium)
Solution: Minimum Area Rectangle
Count Unreachable Pairs of Nodes in an Undirected Graph (medium)
Solution: Count Unreachable Pairs of Nodes in an Undirected Graph
Single Number II (medium)
Solution: Single Number II
4Sum II (medium)
Solution: 4Sum II
Furthest Building You Can Reach (medium)
Solution: Furthest Building You Can Reach
Minimizing Array After Replacing Pairs With Their Product (medium)
Solution: Minimizing Array After Replacing Pairs With Their Product
Fair Distribution of Cookies (medium)
Solution: Fair Distribution of Cookies
Find Leaves of Binary Tree (medium)
Solution: Find Leaves of Binary Tree
Rotate Image (medium)
Solution: Rotate Image
Combination Sum (medium)
Solution: Combination Sum
Implement Trie (Prefix Tree) (medium)
Solution: Implement Trie (Prefix Tree)
Number of Islands (medium)
Solution: Number of Islands
Edit Distance (medium)
Solution: Edit Distance
Container With Most Water (Medium)
Solution: Container With Most Water
Meeting Rooms II (medium)
Solution: Meeting Rooms II
Shortest Subarray with Sum at Least K (hard)
Solution: Shortest Subarray with Sum at Least K
Reverse Pairs (hard)
Solution: Reverse Pairs
Nth Magical Number (hard)
Solution: Nth Magical Number
Candy (hard)
Solution: Candy
Arithmetic Slices II - Subsequence (hard)
Solution: Arithmetic Slices II - Subsequence
Burst Balloons (hard)
Solution: Burst Balloons
Sum of Distances in Tree (hard)
Solution: Sum of Distances in Tree
Maximum Score of a Good Subarray (hard)
Solution: Maximum Score of a Good Subarray
Trapping Rain Water (hard)
Solution: Trapping Rain Water
First Missing Positive (hard)
Solution: First Missing Positive
Solution: Count Nodes Equal to Average of Subtree

Problem Statement

Given the root of a binary tree, return the integer value representing the number of nodes where the node's value is equal to the average of the values in its subtree.

A subtree of the root node contains the root node and all of its descendants.

The average value of n elements is totalSum / n and rounded down to the nearest integer.

Examples

Example 1:

  • Input: [3,1,4,null,2]
Image
  • Expected Output: 3
  • Justification: The node with value 3 has an average of (3+1+4+2)/4 = 2.5 (round down to 2), which doesn't match its value. The node with value 1 has an average of (1+2)/2 = 1.5 (round down to 1), matching its value. The node with value 4 has no children, so its average is 4, matching its value. The node with value 2 is a leaf, so its average is 2, matching its value. Therefore, there are 3 nodes whose value matches the average of their subtree.

Example 2:

  • Input: [5,4,8,3,null,6,7]
Image
  • Expected Output: 4
  • Justification: The root node 5 has an average of (5+4+8+3+6+7)/6 = 5.5 (round down to 5), which matches its value. All leaves with values 3, 6, and 7 match their averages (as they have no children). So, there are a total 4 nodes that matches the given criteria.

Example 3:

  • Input: [10,20,30,40,50,60,70]
Image
  • Expected Output: 4
  • Justification: The leaf nodes (40, 50, 60, 70) have their values equal to their averages as they do not have any children. The other nodes' values do not match the average of their subtrees. Therefore, there are 4 nodes whose values match the average of their subtree.

Solution

To solve this problem, we will employ a depth-first search (DFS) algorithm that traverses the entire binary tree to calculate the sum and count of nodes in each subtree. This approach allows us to compute the average value of a subtree at each node by dividing the total sum of the subtree by the total count of nodes in that subtree. The key reason this approach is effective is because it allows for the simultaneous calculation of sum and count at each node in a single traversal, minimizing the computational complexity.

Our algorithm will recursively visit each node, calculate the sum and count of its subtree, and then determine if the node's value matches the calculated average. By traversing the tree in a depth-first manner, we ensure that all descendants of a node are processed before the node itself, which is crucial for accurate average calculation. This method is chosen for its efficiency in handling tree structures and its ability to solve the problem with minimal overhead.

Step-by-Step Algorithm

  1. Start at the Root: Begin the analysis with the root node of the binary tree.

  2. Recursive Analysis: For each node, recursively analyze both its left and right subtrees to compute the sum of values and the total count of nodes in those subtrees.

  3. Handle Base Case: If the current node is null, indicate that there's no contribution to the sum or count from this subtree by returning a result representing zero sum and zero nodes.

  4. Compute Subtree Results: For a non-null node, combine the results of the left and right subtree analyses with the current node's value to calculate the total sum and total count of nodes for the subtree rooted at this node.

  5. Determine Node Match: Check if the node's value matches the average of the sum of its subtree values. The average is computed as the total sum divided by the total count of nodes, rounded down to the nearest integer. If the node's value matches this average, increment a global count of such matching nodes.

  6. Return Subtree Results: After processing a node, return the computed sum and count of nodes for the subtree rooted at this node to its parent.

  7. Complete the Analysis: Once all nodes have been analyzed, return the total count of nodes whose values match the average of their respective subtrees.

Algorithm Walkthrough

  • The input tree structure:
        5
       / \
      4   8
     /   / \
    3   6   7
    
  1. Start at the Root (Value 5): The root's value is 5, and we begin the analysis here, aiming to explore the entire tree.

  2. Left Subtree (Value 4):

    • Explore left child (value 4), which itself has a left child (value 3).
    • Node 3 is a leaf, so its average matches its value (3/1 = 3). This node matches the criteria.
    • The subtree rooted at node 4 has a sum of 7 (4 from itself and 3 from its left child) and a total count of 2. The average (7/2 = 3) does not match node 4's value, so it is not counted.
  3. Right Subtree (Value 8):

    • Explore right child (value 8), which has two children: 6 (left) and 7 (right).
    • Both children are leaves, so their averages match their values. Nodes 6 and 7 match the criteria, increasing the count.
    • The subtree rooted at node 8 has a sum of 21 (8+6+7) and a count of 3. The average does not match node 8's value, so it is not counted.
  4. Back to the Root:

    • After analyzing both subtrees, the root node aggregates these results: the total sum is 33 (5+7+21 from itself and both subtrees) and the total count of nodes is 6.
    • The average for the root's subtree is 33 divided by 6, which is 5.6, rounded down to 6. Since the root's value is 5, it matches the average, and thus, increment the count to 4.
  5. Conclusion:

    • There are 4 nodes whose values match the average of their subtree.

Code

Java
Saved to Cloud

. . . .

Complexity Analysis

Time Complexity

  • : The algorithm involves a recursive traversal of the binary tree, where N is the number of nodes in the tree. Every node is visited exactly once during the traversal, and for each node, we perform a constant amount of work. Therefore, the time complexity is linear in the number of nodes in the tree.

Space Complexity

  • : The space complexity is determined by the height of the binary tree H, due to the recursive call stack. In the worst case (for a skewed tree), the height of the tree can be N (the number of nodes), resulting in a space complexity of . For a balanced tree, the height H would be log(N), resulting in a space complexity of .
Count Nodes Equal to Average of Subtree (easy)
Find the Difference (easy)
Mark as Completed

On this page

Problem Statement

Examples

Solution

Step-by-Step Algorithm

Algorithm Walkthrough

Code

Complexity Analysis

Time Complexity

Space Complexity